package com.sanhe.rfmuscle.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatSeekBar;

import com.sanhe.rfmuscle.R;

public class TrapezoidSeekBar extends AppCompatSeekBar {

    private static final int TRAPEZOID_PROGRESS_COLOR = 0x1DC6FF;
    private static final int TRAPEZOID_THUMB_WIDTH = 10;
    private static final int TRAPEZOID_THUMB_HEIGHT = 40;

    private Paint progressPaint;
    private int progressColor;
    private Paint thumbPaint;
    private Path trapezoidPath = new Path();
    private Path clipPath = new Path();
    private int trapezoidHeight;

    private float mThumbBitmapWidth;// 拖动按钮位图宽度
    private float mThumbBitmapHeight;// 拖动按钮位图高度
    private Bitmap thumbBitmap;    // 拖动按钮位图

    public TrapezoidSeekBar(Context context) {
        super(context);
        init(context, null);
    }

    public TrapezoidSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public TrapezoidSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        // 从XML属性获取值
        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TrapezoidSeekBar);
            trapezoidHeight = ta.getDimensionPixelSize(
                    R.styleable.TrapezoidSeekBar_seekbar_height, trapezoidHeight);
            progressColor = ta.getColor(
                    R.styleable.TrapezoidSeekBar_seekbar_color, TRAPEZOID_PROGRESS_COLOR);
            mThumbBitmapWidth = ta.getDimensionPixelSize(
                    R.styleable.TrapezoidSeekBar_seekbar_thumb_width, dp2px(TRAPEZOID_THUMB_WIDTH));
            mThumbBitmapHeight = ta.getDimensionPixelSize(
                    R.styleable.TrapezoidSeekBar_seekbar_thumb_height, dp2px(TRAPEZOID_THUMB_HEIGHT));
            setMax(ta.getInt(
                    R.styleable.TrapezoidSeekBar_seekbar_max, 100));
            setProgress(ta.getInt(
                    R.styleable.TrapezoidSeekBar_seekbar_progress, 0));
            ta.recycle();
        }

        // 禁用系统绘制
        setSplitTrack(false);
        setWillNotDraw(false);

        // 初始化进度画笔
        progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        progressPaint.setStyle(Paint.Style.FILL);
        progressPaint.setColor(progressColor);

        // 初始化滑块画笔
        thumbPaint = new Paint();
        thumbPaint.setAntiAlias(true);

        // 初始化滑块位图
        if (mThumbBitmapWidth <= 0) {
            thumbBitmap = null;
        } else {
            thumbBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.energy_thumb);
            thumbBitmap = Bitmap.createScaledBitmap(thumbBitmap, (int) mThumbBitmapWidth, (int) mThumbBitmapHeight, true);
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = trapezoidHeight;
        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        // 获取绘制区域
        int width = getWidth();
        int height = trapezoidHeight;
        int top = getTop();
        int left = getLeft();

        // 创建梯形路径
        float topWidth = width * 0.7f;  // 上底宽度
        float widthDiff = (width - topWidth) / 2; // 两侧宽度差

        trapezoidPath.reset();
        trapezoidPath.moveTo(left + widthDiff, top); // 左上点
        trapezoidPath.lineTo(left + widthDiff + topWidth, top); // 右上点
        trapezoidPath.lineTo(left + width, top + height); // 右下点
        trapezoidPath.lineTo(left, top + height); // 左下点
        trapezoidPath.close();

        // 计算进度位置
        float progressPos = left + (width * getProgress() / (float) getMax());

        // 保存画布状态
        canvas.save();

        // 裁剪进度区域（左侧梯形，右侧垂直）
        clipPath.moveTo(left, top + height);
        clipPath.lineTo(left, top);
        clipPath.lineTo(progressPos, top);
        clipPath.lineTo(progressPos, top + height);
        clipPath.close();
        canvas.clipPath(clipPath);
        clipPath.reset();

        // 绘制进度梯形
        canvas.drawPath(trapezoidPath, progressPaint);

        if (thumbBitmap != null) {
            // 根据进度确定thumb显示高度
            float bitmapTop = top - 5;

            if (progressPos < widthDiff) {
                // thumb位于左斜边
                bitmapTop = bitmapTop + (height - (progressPos / widthDiff * height));
            } else if (progressPos > (width - widthDiff)) {
                // thumb位于右斜边
                bitmapTop = bitmapTop + (height - ((width - progressPos) / widthDiff * height));
            }
            canvas.drawBitmap(thumbBitmap, progressPos - (float) thumbBitmap.getWidth() / 2 - 1,
                    bitmapTop, thumbPaint);
        }

        // 恢复画布状态
        canvas.restore();

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) return false;

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                getParent().requestDisallowInterceptTouchEvent(true);
                setPressed(true);
                if (mOnProgressChangeListener != null) {
                    mOnProgressChangeListener.onStartTrackingTouch(this);
                }
                if (mOnProgressChangeListener != null) {
                    mOnProgressChangeListener.onProgressChanged(this, getProgress(), true);
                }
                updateProgress(event);
                break;

            case MotionEvent.ACTION_MOVE:
                if (mOnProgressChangeListener != null) {
                    mOnProgressChangeListener.onProgressChanged(this, getProgress(), true);
                }
                updateProgress(event);
                break;

            case MotionEvent.ACTION_UP:
                updateProgress(event);
                setPressed(false);
                if (mOnProgressChangeListener != null) {
                    mOnProgressChangeListener.onStopTrackingTouch(this);
                }
                getParent().requestDisallowInterceptTouchEvent(false);
                break;

            case MotionEvent.ACTION_CANCEL:
                setPressed(false);
                if (mOnProgressChangeListener != null) {
                    mOnProgressChangeListener.onStopTrackingTouch(this);
                }
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }

        invalidate();
        return true;
    }

    private void updateProgress(MotionEvent event) {
        float x = event.getX();
        float width = getWidth() - getPaddingLeft() - getPaddingRight();
        int progress = (int) (getMax() * (x - getPaddingLeft()) / width);
        setProgress(Math.max(0, Math.min(progress, getMax())));
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics());
    }

    /**
     * 设置进度
     *
     * @param progress 进度值
     */
    public void setMyProgress(int progress) {
        if (progress > getMax()) progress = getMax();
        if (progress < 0) progress = 0;
        setProgress(Math.max(0, Math.min(progress, getMax())));
        if (null != mOnProgressChangeListener) {
            mOnProgressChangeListener.onProgressChanged(this, progress, false);
        }
        invalidate();
    }


    // endregion -----------------------------------------------------------------------------------
    // region 状态回调 ------------------------------------------------------------------------------

    private OnProgressChangeListener mOnProgressChangeListener;

    public void setOnProgressChangeListener(OnProgressChangeListener onProgressChangeListener) {
        mOnProgressChangeListener = onProgressChangeListener;
    }

    public interface OnProgressChangeListener {
        /**
         * 进度发生变化
         *
         * @param seekBar  拖动条
         * @param progress 当前进度数值
         * @param isUser   是否是用户操作, true 表示用户拖动, false 表示通过代码设置
         */
        void onProgressChanged(TrapezoidSeekBar seekBar, int progress, boolean isUser);

        /**
         * 用户开始拖动
         *
         * @param seekBar 拖动条
         */
        void onStartTrackingTouch(TrapezoidSeekBar seekBar);

        /**
         * 用户结束拖动
         *
         * @param seekBar 拖动条
         */
        void onStopTrackingTouch(TrapezoidSeekBar seekBar);
    }
    // endregion -----------------------------------------------------------------------------------
}